package com.lpb.spring.lpbspring.getway.util;


import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;


public abstract class WebUtils {
    public static String urlEncode(String value, String encoding) {
        if (value == null) {
            return "";
        } else {
            try {
                String encoded = URLEncoder.encode(value, encoding);
                return encoded.replace("+", "%20").replace("*", "%2A").replace("%7E", "~").replace("%2F", "/");
            } catch (UnsupportedEncodingException var3) {
                throw new IllegalArgumentException("FailedToEncodeUri", var3);
            }
        }
    }

    public static String urlDecode(String value, String encoding) {
        if (StringUtils.isBlank(value)) {
            return value;
        } else {
            try {
                return URLDecoder.decode(value, encoding);
            } catch (UnsupportedEncodingException var3) {
                throw new IllegalArgumentException("FailedToDecodeUrl", var3);
            }
        }
    }



    private static String map2querystring(Map<String, ?> map, boolean encode) {
        StringJoiner joiner = new StringJoiner("&");
        map.forEach((name, value) -> {
            if (Objects.isNull(value)) {
                joiner.add(name + "=");
            }else if (value.getClass().isArray()) {
                for (int i=0; i< Array.getLength(value); i++) {
                    Object val = Array.get(value, i);
                    joiner.add(name + "=" + (encode ? urlEncode(val.toString(), "UTF-8") : val.toString()));
                }
            } else if (value instanceof List) {
                ((List<?>) value).forEach(val -> joiner.add(name + "=" + (encode ? urlEncode(val.toString(), "UTF-8") : val.toString())));
            } else {
                joiner.add(name + "=" + (encode ? urlEncode(value.toString(), "UTF-8") : value.toString()));
            }
        });
        return joiner.toString();
    }

    public static String map2querystring0(Map<String, ?> map) {
        return map2querystring(map, false);
    }

    public static String map2querystring(Map<String, ?> map) {
        return map2querystring(map, true);
    }


}
